/**
 * src/pages/chef/dishes/edit/index.tsx
 * ------------------------------------
 * 厨师菜品编辑页面
 * 1. 支持新增菜品与编辑现有菜品
 * 2. 提供菜品信息表单：名称、描述、价格、分类、图片等
 * 3. 分类选择功能，当无分类时提供友好提示
 * 4. 表单验证与提交处理，保存到本地或云端
 * 仅厨师角色可访问，支持快速体验模式与微信登录模式
 * 创建日期：2025-08-06
 */
import { View, Text, Button, Input, Textarea, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState, useEffect } from 'react'
import { useAppContext } from '../../../../store'
import { generateId } from '../../../../utils'
import { Dish } from '../../../../types'
import './index.scss'

export default function EditDish() {
  const { state, dispatch } = useAppContext()
  const { dishes, categories } = state
  const [dish, setDish] = useState({
    id: '',
    name: '',
    description: '',
    price: 0,
    category: '',
    image: '',
    available: true
  })
  const [isEdit, setIsEdit] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  useEffect(() => {
    const params = Taro.getCurrentInstance().router?.params
    if (params?.id) {
      const existingDish = dishes.find(d => d.id === params.id)
      if (existingDish) {
        setDish(existingDish)
        setIsEdit(true)
      }
    }
  }, [dishes])

  const handleSave = () => {
    if (!dish.name.trim()) {
      Taro.showToast({ title: '请输入菜品名称', icon: 'error' })
      return
    }
    
    if (!dish.description.trim()) {
      Taro.showToast({ title: '请输入菜品描述', icon: 'error' })
      return
    }
    
    if (dish.price <= 0) {
      Taro.showToast({ title: '请输入有效价格', icon: 'error' })
      return
    }
    
    if (!dish.category) {
      Taro.showToast({ title: '请选择菜品分类', icon: 'error' })
      return
    }

    setIsSubmitting(true)

    const dishData: Dish = {
      ...dish,
      id: isEdit ? dish.id : generateId(),
      createdAt: isEdit ? (dish as any).createdAt || new Date() : new Date(),
      updatedAt: new Date(),
      createdBy: state.currentUser?.id || ''
    }

    try {
      if (isEdit) {
        dispatch({ type: 'UPDATE_DISH', payload: dishData })
      } else {
        dispatch({ type: 'ADD_DISH', payload: dishData })
      }

      Taro.showToast({ title: '保存成功', icon: 'success' })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    } catch (error) {
      Taro.showToast({ title: '保存失败', icon: 'error' })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleImageUpload = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        setDish({ ...dish, image: tempFilePath })
        Taro.showToast({ title: '图片上传成功', icon: 'success' })
      },
      fail: () => {
        Taro.showToast({ title: '图片上传失败', icon: 'error' })
      }
    })
  }

  const getCategoryName = (categoryId: string) => {
    const category = categories.find(cat => cat.id === categoryId)
    return category?.name || '未分类'
  }

  return (
    <View className='dish-edit'>
      <View className='header'>
        <Text className='title'>{isEdit ? '编辑菜品' : '添加菜品'}</Text>
      </View>

      <View className='form'>
        <View className='form-item'>
          <Text className='label'>菜品名称 *</Text>
          <Input
            className='input'
            value={dish.name}
            onInput={(e) => setDish({ ...dish, name: e.detail.value })}
            placeholder='请输入菜品名称'
            maxlength={20}
          />
        </View>

        <View className='form-item'>
          <Text className='label'>菜品描述 *</Text>
          <Textarea
            className='textarea'
            value={dish.description}
            onInput={(e) => setDish({ ...dish, description: e.detail.value })}
            placeholder='请输入菜品描述'
            maxlength={200}
          />
        </View>

        <View className='form-item'>
          <Text className='label'>价格 *</Text>
          <Input
            className='input'
            type='digit'
            value={dish.price.toString()}
            onInput={(e) => setDish({ ...dish, price: parseFloat(e.detail.value) || 0 })}
            placeholder='请输入价格'
          />
        </View>

        <View className='form-item'>
          <Text className='label'>分类 *</Text>
          <View className='category-select'>
            {categories.length > 0 ? (
              categories.map(category => (
                <View
                  key={category.id}
                  className={`category-option ${dish.category === category.id ? 'selected' : ''}`}
                  onClick={() => setDish({ ...dish, category: category.id })}
                >
                  <Text>{category.name}</Text>
                </View>
              ))
            ) : (
              <View className='no-categories'>
                <Text className='no-categories-text'>暂无分类</Text>
                <Text className='no-categories-desc'>请先添加菜品分类</Text>
              </View>
            )}
          </View>
          {categories.length === 0 && (
            <Button 
              className='add-category-btn' 
              onClick={() => {
                Taro.showModal({
                  title: '添加分类',
                  content: '请先添加菜品分类，然后再添加菜品',
                  showCancel: false
                })
              }}
            >
              添加分类
            </Button>
          )}
        </View>

        <View className='form-item'>
          <Text className='label'>菜品图片</Text>
          {dish.image ? (
            <View className='image-preview'>
              <Image src={dish.image} className='preview-img' mode='aspectFill' />
              <Button className='change-img-btn' onClick={handleImageUpload}>
                更换图片
              </Button>
            </View>
          ) : (
            <View className='image-upload' onClick={handleImageUpload}>
              <View className='upload-icon'>📷</View>
              <Text className='upload-text'>点击上传图片</Text>
            </View>
          )}
        </View>

        <View className='form-item'>
          <Text className='label'>状态</Text>
          <View className='status-toggle'>
            <View
              className={`toggle-option ${dish.available ? 'selected' : ''}`}
              onClick={() => setDish({ ...dish, available: true })}
            >
              <Text>可售</Text>
            </View>
            <View
              className={`toggle-option ${!dish.available ? 'selected' : ''}`}
              onClick={() => setDish({ ...dish, available: false })}
            >
              <Text>停售</Text>
            </View>
          </View>
        </View>
      </View>

      <View className='actions'>
        <Button className='cancel-btn' onClick={() => Taro.navigateBack()}>
          取消
        </Button>
        <Button 
          className='save-btn' 
          onClick={handleSave}
          disabled={isSubmitting}
        >
          {isSubmitting ? '保存中...' : '保存'}
        </Button>
      </View>
    </View>
  )
} 